package com.oops.service;

import com.oops.mapper.TGoodsMapper;
import com.oops.model.TGoods;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class GoodsService {
    private final TGoodsMapper tGoodsMapper;

    public GoodsService(TGoodsMapper tGoodsMapper) {
        this.tGoodsMapper = tGoodsMapper;
    }

    /**
     * TODO: 扣除商品库存
     *
     * @author wuyijie
     * @date 2022/4/16 19:11
     * @param goodsId 商品ID
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void decreaseGoodsInventory(long goodsId) {
        try {
            TGoods tGoods = tGoodsMapper.selectById(goodsId);
            tGoods.setInventory(tGoods.getInventory() - 1);
            tGoodsMapper.updateById(tGoods);
            log.info("decreaseGoodsInventory success,goods:{}", tGoods);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("decreaseGoodsInventory failed，goodsId:{}",goodsId);
            throw new RuntimeException("decreaseGoodsInventory failed");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void increaseGoodsInventory(long goodsId) {
        try {
            TGoods tGoods = tGoodsMapper.selectById(goodsId);
            tGoods.setInventory(tGoods.getInventory() + 1);
            tGoodsMapper.updateById(tGoods);
            log.info("increaseGoodsInventory success,goods:{}", tGoods);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("increaseGoodsInventory failed，goodsId:{}",goodsId);
            throw new RuntimeException("increaseGoodsInventory failed");
        }
    }
}
